package gen.tools.modUnit;

import gen.tools.Widgets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mailGenerator.MailGenerator;

public class ApproveAddModUnit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ApproveAddModUnit() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		
		/*
		 * 1. 檢查這筆資料是不是還在(沒有其它主管先回覆了) 
		 * 2. 修改變更申請的狀態
		 * 3. 創建 SVN CM的資料夾
		 * 4. 刪除todolist
		 * 	寄發通知信
		 * */
		
		final boolean isApprove = Integer.parseInt(request.getParameter("isApprove"))==1?true:false;	//主管是否同意
		final int craId = wid.getParNumberFromRequest( request.getParameter("craId") );	//變更申請ID
		final int toDoListId = wid.getParNumberFromRequest( request.getParameter("toDoListId") );
		final String subsysId = request.getParameter("subsysId");
		final String modUnitId = request.getParameter("modUnitId");
		final String applierId = request.getParameter("creatorId");
		final String empId = request.getParameter("empId");
		final int changeTypeId = (isApprove?3:4);
		
		String strSQL;
		String res = null;
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		ArrayList<String> connSVNInfo;
		
		try {
			
			conn = wid.getConn();
			
			/****檢查有沒有其它主管先回覆了****/
			strSQL="SELECT craStatusId FROM cramain WHERE craId=?";
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, craId);
			rs = ps.executeQuery();
			rs.next();
			if ( rs.getInt(1)==2 ) {	//表示仍處於待審的狀態
				
				/****建立LOG，第一步就開始記錄程式的執行****/
				conn.setAutoCommit(false);
				strSQL="INSERT INTO changelog (changeLogId,changeTypeId,creatorId,bDate) VALUES (null,"+changeTypeId+",?,?)";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, empId);
				ps.setTimestamp(2, wid.cDT());
				ps.execute();
				strSQL="SELECT MAX(changeLogId) FROM changelog";
				ps = conn.prepareStatement(strSQL);
				rs = ps.executeQuery();
				rs.next();
				final int clId4Approve = rs.getInt(1);
				conn.commit();
				conn.setAutoCommit(true);
				
				//修改變更申請的狀態
				strSQL = "UPDATE cramain SET craStatusId=? WHERE craId=?";
				ps = conn.prepareStatement(strSQL);
				ps.setInt(1, changeTypeId);
				ps.setInt(2, craId);
				ps.execute();
				
				//取得提出者的寄件地址
				final String mailList[] = wid.getEmailAddr(applierId);
				
				//刪除已完成的待辦事項，將其加入待辦清單
				wid.completedList(toDoListId, applierId);
		
				
				//信件內容
				final MailGenerator mg = new MailGenerator();
				final String mailBody = mg.mailBodyMail(isApprove?1:2,wid.getEmpName(empId));
				final String mailSubject = mg.subjectMail(isApprove?1:2);
				
				if ( isApprove ) {
					final String urlJobStr = wid.JENKINSURL+"api/xml";
					final String urlStr = wid.JENKINSURL+"createItem?name=";
					
					//創建 SVN CM的資料夾
					connSVNInfo = wid.getSVN4SubsysConnInfo(subsysId,1);	//SVN CM MR的連線方式
					wid.creDirInSVN(connSVNInfo.get(0),connSVNInfo.get(1),connSVNInfo.get(2),modUnitId,false);
					
					//建立jenkins中  MR的JOB
					String jobName = "MR_"+subsysId+"_"+modUnitId;
					boolean isJobExistInJenkins = wid.isJobExistInJenkins(jobName,false,urlJobStr,"","");		
					if (!isJobExistInJenkins) {	//不存在，所以要新建
						wid.creJobInJenkins(modUnitId,subsysId,connSVNInfo.get(0),true,false,urlStr,"","");
						wid.updateJobPostBuildURL(jobName,0,null,0,null,0,null);
					}
					
					connSVNInfo = wid.getSVN4SubsysConnInfo(subsysId,2);	//SVN CM OL的連線方式
					wid.creDirInSVN(connSVNInfo.get(0),connSVNInfo.get(1),connSVNInfo.get(2),modUnitId,false);
					
					//建立jenkins中  OL的JOB
					jobName = "OL_"+subsysId+"_"+modUnitId;
					isJobExistInJenkins = wid.isJobExistInJenkins("OL_"+subsysId+"_"+modUnitId,false,urlJobStr,"","");		
					if (!isJobExistInJenkins) {	//不存在，所以要新建
						wid.creJobInJenkins(modUnitId,subsysId,connSVNInfo.get(0),false,false,urlStr,"","");
						wid.updateJobPostBuildURL(jobName, 0,null,0,null, 0,null);
					}
					
					
					//因為同意又再分兩階段  1.同意後配置(status 3)，2. 配置且成功(status 5)，故此時因為完成了1, 故要將狀態設為5
					strSQL = "UPDATE cramain SET craStatusId=? WHERE craId=?";
					ps = conn.prepareStatement(strSQL);
					ps.setInt(1, 5);
					ps.setInt(2, craId);
					ps.execute();
				}
				
				
				
				//寄發通知信
				wid.sendMailMain(mailList, mailSubject, mailBody);
				
				/****完成這次的異動****/
				strSQL = "UPDATE changelog SET eDate=? WHERE changeLogId=?";
				ps = conn.prepareStatement(strSQL);
				ps.setTimestamp(1, wid.cDT());
				ps.setInt(2, clId4Approve);
				ps.execute();
				
				res="OK";
			}
		} catch(Exception e) {
			res = wid.errProcess(e);
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		response.getWriter().write(res);
	}

}
